<template>
  <div style="margin-top:-20px;">
    <a-upload
      name="file"
      accept=".png,.jpg,.jpeg,.gif"
      :data="param"
      :action="API_URL+'/zg-system/file/upload'"
      @change="handleChange"
      :headers="headers"
      :showUploadList="false"
      :beforeUpload="handleBeforeUpload"
    >
      <a-button ref="upload" style="display:none"> <a-icon type="upload" /> 上传图片 </a-button>
    </a-upload>
    <editor :key="timer" :init="tinymceInit" v-model="content"></editor>
  </div>
</template>

<script>
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver'
import 'tinymce/icons/default/icons'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/preview'
import 'tinymce/plugins/fullscreen'
export default {
  components: {
    Editor
  },
  model: {
    prop: 'modelVal', // 指向props的参数名
    event: 'change'// 事件名称
  },
  props: {
    id: {
      type: String,
      default: 'default'
    },
    height: {
      type: Number,
      default: 0
    },
    modelVal: {
      type: String,
      default: '本地图片上传功能仅为演示，实际使用需要补全图片存储地址'
    }
  },
  data () {
    return {
      timer: '',
      param: {
        module: 'default'
      },
      headers: {},
      size: 20,
      tinymceInit: {},
      content: this.modelVal
    }
  },
  mounted () {
    this.headers[ACCESS_TOKEN] = storage.get(ACCESS_TOKEN)
    this.open()
  },
  created () {
    const that = this
    that.tinymceInit = {
      relative_urls: false,
      remove_script_host: false,
      fontsize_formats: '8pt 10pt 12pt 14pt 18pt 24pt 36pt',
      font_formats: "Arial='Arial',Helvetica,Arial,sans-serif;Times New Roman='Times New Roman',Helvetica,Arial,sans-serif;宋体='宋体',Helvetica,Arial,sans-serif;仿宋='仿宋',Helvetica,Arial,sans-serif;仿宋GB2312='仿宋GB2312',Helvetica,Arial,sans-serif;楷体='楷体',Helvetica,Arial,sans-serif;黑体='黑体',Helvetica,Arial,sans-serif;华文新魏='华文新魏',Helvetica,Arial,sans-serif;隶书='隶书',Helvetica,Arial,sans-serif",
      autosave_interval: '20s',
      image_advtab: true,
      table_default_styles: {
        width: '100%',
        borderCollapse: 'collapse'
      },
      content_css: process.env.VUE_APP_BASE + 'tinymce/skins/ui/oxide/content.css',
      skin_url: process.env.VUE_APP_BASE + 'tinymce/skins/ui/oxide',
      language_url: process.env.VUE_APP_BASE + 'tinymce/langs/zh_CN.js',
      language: 'zh_CN',
      height: that.height === 0 ? (document.body.offsetHeight - 300) : that.height,
      browser_spellcheck: true, // 拼写检查
      branding: false, // 去水印
      statusbar: false, // 隐藏编辑器底部的状态栏
      paste_data_images: true, // 允许粘贴图像
      menubar: false, // 隐藏最上方menu
      plugins: 'advlist table lists paste preview fullscreen',
      toolbar: [
        'fontselect fontsizeselect forecolor backcolor bold italic underline strikethrough',
        'alignleft aligncenter alignright alignjustify imageUpload quicklink h2 h3 blockquote table numlist bullist preview fullscreen'
      ],
      /**
       * 下面方法是为tinymce添加自定义插入图片按钮
       * 借助iview的Upload组件,将图片先上传到存储云上，再将图片的存储地址放入编辑器内容
       */
      setup: (editor) => {
        editor.on('change', function (e) {
          that.content = editor.getContent()
        })
        editor.ui.registry.addButton('imageUpload', {
          tooltip: '允许.png,.jpg,.jpeg,.gif等格式，大小不超过20MB',
          icon: 'image',
          onAction: () => {
            that.$refs.upload.$el.click()
          }
        })
      }
    }
  },
  watch: {
    modelVal (newVal) {
      this.content = newVal
    },
    content (newVal) {
      this.$emit('change', newVal)
    }
  },
  methods: {
    open () {
      this.timer = new Date().getTime()
    },
    insertImage (src) {
      tinymce.execCommand('mceInsertContent', false, `<img src=${src}>`)
    },
    setContent (content) {
      this.content = content
    },
    getContent () {
      return this.content
    },
    handleBeforeUpload (file) {
      const sizeIsRight = file.size / 1024 / 1024 < this.size
      if (!sizeIsRight) {
        this.$error({ title: `${file.name}超过${this.size}MB，不允许上传` })
        return false
      }
      return true
    },
    handleChange (info) {
      const status = info.file.status
      if (status === 'done') {
        const res = info.file.response
        if (res.code !== 1) {
          this.$error({ title: res.msg })
        } else {
          const json = res.data
          this.insertImage(this.MINIO_URL + json.path)
        }
      } else if (status === 'error') {
        this.$error({ title: `${info.file.name} 文件上传失败.` })
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
